using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Text.RegularExpressions;

public partial class Pages_Employee_ManageDeliveries_AddDelivery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    /// <summary>
    /// Checks whether the Weight field is a positive float number or not
    /// </summary>
    /// <param name="source"></param>
    /// <param name="args"></param>
    protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
    {
        try
        {
            float n = float.Parse(txtWeight.Text);
            args.IsValid = (n > 0);
        }
        catch (FormatException ex)
        {
            args.IsValid = false;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid) return;

        // getting the fields value
        int customerID = Int32.Parse(txtCustomerID.Text.Trim());
        string type = ddlType.SelectedItem.Text;
        int serviceID = Int32.Parse(ddlService.SelectedValue);
        float weight = float.Parse(txtWeight.Text.Trim());
        int distanceID = Int32.Parse(ddlDistance.SelectedValue);
        string receiverName = txtReceiverName.Text.Trim();
        string receiverAddress = txtReceiverAddress.Text.Trim();
        int receiverCityID = Int32.Parse(ddlReceiverCity.SelectedValue);

        int deliverableID;
        try
        {
            // the return value is the ID of the Deliverable record 
            // which has just inserted successfully
            deliverableID = DALDeliverable.InsertDeliverable(customerID, type, serviceID, weight, distanceID, receiverName, receiverAddress, receiverCityID);
            if (deliverableID > 0)
            {
                lblMessage.Text = "Added successfully. Please click to view the ";
                // show link to Invoice page
                lnkInvoice.Text = "Invoice";
                DisableFields();
                // save the Deliveable ID and Customer ID for the invoice
                Session["CreatedDeliverableID"] = deliverableID;
                Session["CurrentCustomerID"] = customerID;
            }
            else
                lblMessage.Text = "Error on adding deliverable";
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error on adding deliverable. Please note that customer ID must exists.";
        }
    }

    private void DisableFields()
    {
        txtCustomerID.ReadOnly = true;
        ddlType.Enabled = false;
        ddlService.Enabled = false;
        txtWeight.ReadOnly = true;
        ddlDistance.Enabled = false;
        txtReceiverName.ReadOnly = true;
        txtReceiverAddress.ReadOnly = true;
        ddlReceiverCity.Enabled = false;
        btnSubmit.Enabled = false;
        btnReset.Enabled = false;
        lnkNewCustomer.Text = "";
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";
        lnkInvoice.Text = "";
        txtCustomerID.Text = "";
        ddlType.SelectedIndex = 0;
        ddlService.SelectedIndex = 0;
        txtWeight.Text = "";
        ddlDistance.SelectedIndex = 0;
        txtReceiverName.Text = "";
        txtReceiverAddress.Text = "";
        ddlReceiverCity.SelectedIndex = 0;
        txtCustomerID.Focus();
    }

    /// <summary>
    /// This webmethod checks whether a customer ID is existed
    /// </summary>
    /// <param name="id">id</param>
    /// <returns>1 if the parameter is an id of an existed customer, 0 otherwise, -1 if id string is not a valid id</returns>
    [WebMethod]
    public static int IsExistedID(string id)
    {
        Regex idPattern = new Regex("^[1-9][0-9]*$");
        if (!idPattern.IsMatch(id))
            return -1;
        int n = Int32.Parse(id);
        if (DALCustomers.GetCustomersByID(n).Count != 0)
            return 1;
        else
            return 0;
    }

    /// <summary>
    /// Calculate charge for the delivery, create new invoice and insert it to database,
    /// then open the Invoice page in a new window
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lnkInvoice_Click(object sender, EventArgs e)
    {
        lnkInvoice.Enabled = false;
        decimal charge;
        try
        {
            // calculate charge
            int serviceID = Int32.Parse(ddlService.SelectedValue);
            float weight = float.Parse(txtWeight.Text.Trim());
            int distanceID = Int32.Parse(ddlDistance.SelectedValue);
            charge = DALInvoice.CalculatePrice(weight, distanceID, serviceID);
        }
        catch
        {
            lblMessage.Text = "Error on calculating price";
            return;
        }
        int deliverableID = Int32.Parse(Session["CreatedDeliverableID"].ToString());
        // call InsertInvoice to insert new invoice to database
        InsertInvoice(deliverableID, charge);
    }

    protected void InsertInvoice(int deliverableID, decimal charge)
    {
        string userName = User.Identity.Name;
        int affected; 
        try
        {
            affected = DALInvoice.InsertInvoice(deliverableID, userName, DateTime.Now.ToString("MM/dd/yyyy"), charge);
            if (affected > 0)
                OpenNewWindow("Invoice.aspx");
            else
            {
                lblMessage.Text = "Error on creating invoice";
                lnkInvoice.Text = "";
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error on creating invoice";
            lnkInvoice.Text = "";
        }
    }

    private void OpenNewWindow(string newWindowUrl)
    {
        if (!ClientScript.IsClientScriptBlockRegistered("window.open"))
        {
            string javaScript =
              "<script type='text/javascript'>\n" +
              "<!--\n" +
              "window.open('" + newWindowUrl + "');\n" +
              "// -->\n" +
              "</script>\n";
            this.RegisterStartupScript("", javaScript);
        }
        else
        {
            Response.Redirect(newWindowUrl);
        }
    }
}
